<template>
  <div class="chat-interface">
    <!-- 联系人头像和头衔区域 -->
    <div class="contact-info" v-if="currentContact">
      <img :src="currentContact.avatar" alt="Avatar" class="avatar" />
      <span class="contact-title">{{ currentContact.name }}</span>
    </div>
    <!-- 聊天消息显示区域 -->
    <div id="chat" class="chat-messages" v-if="currentContact">
      <div
        v-for="(message, index) in currentContact.messages"
        :key="index"
        :class="['chat-message', { 'self-message': message.sender === username}]"
      >
        <img
          :src="message.sender !==username ? 'https://picsum.photos/30/30' : currentContact.avatar"
          alt="Avatar"
          class="message-avatar"
        />
        <div class="message-content">
          <!-- <span>{{ message.content }}</span> -->
          <div v-html="parseMessageContent(message.content)"></div>
          <span class="message-time">{{ message.time }}</span>
        </div>
      </div>
    </div>
    <!-- 消息输入框和发送相关区域 -->
    <div class="message-input-area" v-if="currentContact">
      <!-- 新增的图标区域，留出空间并添加图标 -->
      <div class="icon-section">
        <!-- 使用导入的PNG图片 -->
        <img :src="smileImg" alt="Smile" class="smile-icon" @click="openEmojiPicker" />
        <img :src="fileUploadImg" alt="File Upload" class="file-upload-icon" @click="openFilePicker" />
        <i class="fa-regular fa-file" @click="openFilePicker" />
      </div>
      <!-- 消息输入框和发送按钮区域 -->
      <div class="input-and-send">
        <textarea
          v-model="newMessage"
          placeholder="输入消息..."
          class="message-input"
        ></textarea>
        <button @click="sendMessage" class="send-button">发送</button>
      </div>
    </div>
    <div v-else class="no-contact-selected">请选择一个联系人开始聊天</div>
    <!-- 引入表情选择框组件 -->
    <EmojiPicker :isVisible="emojiStore.isEmojiVisible" @sendEmoji="handleSendEmoji" />
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect,watch,computed,nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { useContactStore } from '@/stores/contacts';
import smileImg from '@/assets/icons/smile.png';
import fileUploadImg from '@/assets/icons/file_upload.png';
import EmojiPicker from '@/components/chat/emoji/Emoji.vue'
import {useEmojiStore} from '@/stores/emoji'
import request from '@/axios/index'
const emojiStore = useEmojiStore()

const route = useRoute();
const contactStore = useContactStore();
const username = ref();

const contactId = ref(route.query.contactId);
const friendId = ref(route.query.friendId);

// 聊天相关数据
const currentContact = ref(null);
const newMessage = ref('');

// 初始联系人
const contacts = computed(()=>contactStore.contacts);

watch(() => route.query.contactId, (newId) => {
  console.log('contactId变化:', newId);
  contactId.value = newId;
});

watch(() => route.query.friendId, (newId) => {
  console.log('friendId变化:', newId);
  friendId.value = newId;
});


const createChat = (friendName,id)=>{
    request.post('/chat-conversation/create',{
      friendId: friendName,
      orderNo: id,
    }).then((res)=>{
      console.log("创建聊天框成功：",res);
    })
}

watchEffect(() => {
    if(contactId.value!=undefined){
      console.log("id变化了");
      const target = contacts.value.find(c => c.id == contactId.value);
      if (target) {
        currentContact.value = target;
      }
    }
    else if(friendId.value!=undefined){
      const tar = contacts.value.find(c => c.name == friendId.value);
      if(tar) currentContact.value = tar;
      else {
        const now =Date.now().toString();
        const cur = {
          id: now,
          name: friendId.value,
          avatar: 'https://picsum.photos/50/50',
          messages: [],
          unreadCount: 0
        };
        contactStore.addContact(cur);
        createChat(friendId.value,now);
        currentContact.value = cur;
      }
    }
});
const EMOJI_PREFIX = '[UNIVERSAL_EXCLUSIVE_EMOTICON_IDENTIFIER_V2025_]';
// 解析消息内容，处理表情
const parseMessageContent = (content) => {
  if (!content || typeof content!=='string') {
    return content;
  }
  if (content.startsWith(EMOJI_PREFIX)) {
    const emojiName = content.substring(EMOJI_PREFIX.length);
    const emojipath = emojiStore.emojiList.find(c=> c.name ===emojiName).path;
    return `<img src="${emojipath}" alt="emoji" style="width: 24px; height: 24px; margin: 0 2px; vertical-align: middle;">`;
  }

  return `<span>${content}</span>`;
};

function setupSocketListeners() {
  window.electronAPI.socket.onMessage((msgStr) => {
    console.log('收到消息：', msgStr); // 此时 msg 是对象
    const msgWrapper = msgStr;
    const contentObj = msgWrapper.content;

    console.log('收到消息：', contentObj);
    if (
      msgWrapper.type === 1 &&
      currentContact.value &&
      (
        (contentObj.senderId === currentContact.value.name && contentObj.receiverId === username.value) ||
        (contentObj.senderId === username.value && contentObj.receiverId === currentContact.value.name)
      )
    ){
      console.log("contentObj.senderId：",currentContact.value.name)
      const isSelf = contentObj.senderId === username.value;
      currentContact.value.messages.push({
        sender: isSelf ? username.value : currentContact.value.name,
        content: contentObj.content,
        time: new Date().toLocaleTimeString()
      });
    }
  });
}
onMounted(()=>{
  window.electronAPI.getUsername().then((res)=>{
  username.value = res;
})
  // setupSocketListeners();
})

function formatDateTime(date) {
  const pad = n => n.toString().padStart(2, '0');
  const y = date.getFullYear();
  const m = pad(date.getMonth() + 1);
  const d = pad(date.getDate());
  const h = pad(date.getHours());
  const min = pad(date.getMinutes());
  const s = pad(date.getSeconds());
  return `${y}-${m}-${d} ${h}:${min}:${s}`;
}



function sendMessage() {
  if (!newMessage.value.trim()) return;

  const content = {
    senderId: username.value, 
    receiverId: currentContact.value.name,
    content: newMessage.value
  };

  const msg = {
    type: 0, // 单聊
    content: JSON.stringify(content)
  };
  console.log("username:",username.value)
  console.log("msg：",msg);

  window.electronAPI.socket.send({
    type: '0x01', // 单聊
    content: JSON.stringify(msg)
  });

  const curDate = new Date();
  currentContact.value.messages.push({
    sender: username.value,
    content: newMessage.value,
    time: formatDateTime(curDate),
  });
  // contactStore.add({
  //   sender: username.value,
  //   content: newMessage.value,
  //   time: formatDateTime(curDate),
  // });


  console.log("消息：",currentContact.value.messages)
  nextTick(() => {
          const chatWindow = document.getElementById('chat');
          chatWindow.scrollTop = chatWindow.scrollHeight;
        });
  newMessage.value = '';
}


function openEmojiPicker() {
  emojiStore.openEmoji(); // 显示表情选择框
  console.log("isEmojiVisible",emojiStore.isEmojiVisible.value)
}

watch(emojiStore.isEmojiVisible,()=>{

})

function handleSendEmoji(emojiName) {
  // 处理发送表情的逻辑
  console.log('发送表情:', emojiName);
  
  const content = {
    senderId: username.value, 
    receiverId: currentContact.value.name,
    content: '[UNIVERSAL_EXCLUSIVE_EMOTICON_IDENTIFIER_V2025_]'+emojiName
  };

  const msg = {
    type: 4, // 单聊
    content: JSON.stringify(content)
  };
  console.log("username:",username.value)
  console.log("msg：",msg);

  window.electronAPI.socket.send({
    type: '0x04', // 单聊
    content: JSON.stringify(msg)
  });

  currentContact.value.messages.push({
    sender: username.value,
    content:'[UNIVERSAL_EXCLUSIVE_EMOTICON_IDENTIFIER_V2025_]'+emojiName,
    time: formatDateTime(new Date()),
  });
  console.log("表情消息：",emojiName)
  nextTick(() => {
          const chatWindow = document.getElementById('chat');
          chatWindow.scrollTop = chatWindow.scrollHeight;
        });
  // 在这里添加发送表情的代码
}

function openFilePicker() {
  console.log('文件上传功能未实现');
}
</script>


<style scoped>
/* 设置所有元素使用 border-box 盒模型 */
*,
*::before,
*::after {
  box-sizing: border-box;
}
body {
  margin: 0;
  padding: 0;
}
.chat-interface {
  height: 100vh;
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  overflow: hidden;
}

.contact-info {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f5f5f5;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.contact-title {
  font-weight: bold;
  font-size: 18px;
}

.chat-messages {
  flex: 0.95;
  overflow-y: auto;
  padding: 15px;
  background-color: #f9f9f9;
}

.chat-message {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
}

.self-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin: 0 8px;
}

.message-content {
  background-color: #e0f7fa;
  padding: 8px 12px;
  border-radius: 8px;
  max-width: 70%;
  position: relative;
  word-wrap: break-word;
  word-break: normal;
  overflow-wrap: break-word;
  white-space: pre-wrap;
  box-sizing: border-box;
  max-inline-size: 100%;
  min-inline-size: 0;
}

.self-message .message-content {
  background-color: #95ec69;
}

.message-time {
  width: 105px;
  font-size: 10px;
  color: #777;
  position: absolute;
  bottom: -12px;
  right: 5px;
}

.message-input-area {
  display: flex;
  flex-direction: column; /* 修改为 column 布局，使图标区域和输入框区域垂直排列 */

  padding: 15px;
  border-top: 1px solid #e0e0e0;
  background-color: #f5f5f5;

}

/* 新增的图标区域样式 */
.icon-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px; /* 留出图标和输入框之间的空间 */
  justify-content: flex-start; /* 添加这一行，使图标左对齐 */
}

.input-and-send {
  flex: 1;
  display: flex;
  width: 100%; /* 使输入框和发送按钮区域占满宽度 */
}

.message-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  margin-right: 10px;
  resize: none;
}

.send-button {
  padding: 8px 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.send-button:hover {
  background-color: #0056b3;
}

.no-contact-selected {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #777;
}

/* 图标样式 */
.fa-regular {
  font-size: 20px;
  cursor: pointer;
  margin-right: 10px; /* 图标之间的间距 */
  margin-bottom: 0;
}

/* 微笑图片样式 */
.smile-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
  margin-right: 10px;
}

/* 文件上传图片样式 */
.file-upload-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
  margin-right: 10px;
}
.emoji-image {
  width: 24px;
  height: 24px;
  margin: 0 2px;
  vertical-align: middle;
}
</style>